package com.maybach.util;

import com.lowagie.text.pdf.BaseFont;
import org.apache.commons.lang.StringEscapeUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.UUID;

/**
 * Created by songshuang on 16/3/7.
 */
public class PdfUtil {


    public static Logger log = LoggerFactory.getLogger(PdfUtil.class);

    public static String exportPdfFile(String urlStr, String pdfTempPath, String fontPath) throws Exception {
        String outputFile = UUID.randomUUID() + ".pdf";
        OutputStream os = null;
        File f = new File(pdfTempPath);
        if(!f.exists()){
            f.mkdirs();
        }
        try {
            os = new FileOutputStream(pdfTempPath  +File.separator+ outputFile);
            ITextRenderer renderer = new ITextRenderer();
            String str = getHtmlFile(urlStr);
            renderer.setDocumentFromString(str);
            ITextFontResolver fontResolver = renderer.getFontResolver();
            fontResolver.addFont(fontPath + "/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            fontResolver.addFont(fontPath + "/Arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            renderer.layout();
            renderer.createPDF(os);
            os.flush();
            return outputFile;
        } catch (Exception e) {
            log.error("pdf error,url="+urlStr,e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (Exception e) {
                }
            }
        }
        return null;
    }
    public static String getHtmlFile(String urlStr) throws Exception {
        Document parse = Jsoup.parse(new URL(urlStr), 6000);
        return StringEscapeUtils.unescapeHtml(parse.outerHtml());
    }

    public static void createPDF(HttpServletResponse response, String fontPath, String text, String fileName) {
        if (StringUtil.isBlank(text)) {
            return;
        }
        OutputStream os = null;
        try {
            ITextRenderer renderer = new ITextRenderer();
            os = response.getOutputStream();
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8") + ".pdf");
            response.setContentType("application/pdf");// 定义输出类型
            renderer.setDocumentFromString(text);
            ITextFontResolver fontResolver = renderer.getFontResolver();
            fontResolver.addFont(fontPath + "/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            fontResolver.addFont(fontPath + "/Arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            renderer.layout();
            renderer.createPDF(os);
            os.flush();
        } catch (Exception e) {
            log.error("", e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (Exception e) {
                    log.error("", e);
                }
            }
        }
    }
}
